﻿using System.Text.RegularExpressions;
using Gumini.JulaDB.DataTypes;

namespace Gumini.JulaDB.Expressions.Operators
{
    internal class LikeOperator : BinaryOperator
    {
        public LikeOperator()
            : base("like") { }
    
        public override TypedValue Evaluate(TypedValue a, TypedValue b)
        {
            var varcharType = DataType.Varchar;
            return new TypedValue(DataType.Bool, Like(
                (string)varcharType.ConvertFrom(a.Value),
                (string)varcharType.ConvertFrom(b.Value)));
        }

        private static bool Like(string toSearch, string toFind)
        {
            // taken from:
            // http://stackoverflow.com/questions/5417070/c-sharp-version-of-sql-like
            return new Regex(@"\A" + new Regex(@"\.|\$|\^|\{|\[|\(|\||\)|\*|\+|\?|\\").
                Replace(toFind, ch => @"\" + ch).Replace('_', '.').Replace("%", ".*") + @"\z", RegexOptions.Singleline).
                IsMatch(toSearch);
        }

        public override DataType GetReturnType()
        {
            return DataType.Bool;
        }
    }
}
